package sensimulator;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import sennetwork.NetworkClient;
import sennetworkserver.LaneStore;
import sennetworkserver.TrafficLight;
import sensimulator.intersection.Intersection;

/**
 * Main class that manages other classes
 * @author Erwin
 */
public class Simulator implements Runnable {

	static final int UPDATE_INTERVAL = 20;
	
	private InputFileReader inputFileReader;
	
	private Intersection intersection;
	
	private Thread mainThread;
	
	private NetworkClient networkClient;
	
	private long time;
	
	private long lastTick;
	
	private Simulator(String networkHost, int networkPort, String inputFile) {
		intersection = new Intersection();
		inputFileReader = new InputFileReader();
	
		try { inputFileReader.read(inputFile); }
		catch (IOException e) { 
			System.out.println("Failed to read input file! (" + e.getMessage() + ") generating one..");
			inputFileReader.generate(1000, 10 * 60 * 1000);
		}
		
		inputFileReader.schedule();

		networkClient = new NetworkClient(networkHost, networkPort);
		//networkClient = new NetworkClient("141.252.216.163", 1337);
		//networkClient = new NetworkClient("141.252.222.195", 1337);
		//networkClient = new NetworkClient("141.252.218.247", 1337);
		
		mainThread = new Thread(this);
		mainThread.start();
	}

	@Override
	public void run() {
		time = lastTick = 0;
				
//		for (int i = 1; i <= 28; i++)
//			LaneStore.getLane(i).getTrafficLight().setState(TrafficLight.GREEN);
		
		while (true) {
			time = System.currentTimeMillis();
			intersection.tick(time, (int) (time - lastTick));
			lastTick = time;			
			
			try { Thread.sleep(UPDATE_INTERVAL); }
			catch (InterruptedException ex) { break; }
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length < 2)
			System.out.println("Usage: Simulator controllerHost controllerPort inputfile");
		else
			new Simulator(args[0], Integer.parseInt(args[1]), args.length >= 3 ? args[2] : "");
	}


}
